# -*- codeing = utf-8 -*-
# @Time : 2022/7/19 15:37
# @Author : ZN
# @Email : 747723508@qq.com
# @File : serializers.py
# @Software: PyCharm
from rest_framework import  serializers
from .models import *
class StudentSerializer(serializers.ModelSerializer):
    # classes = serializers.StringRelatedField(label='班级') #重写 原本classes = classes.id 现在classes=classes.__str__()
    class_name = serializers.CharField(source='classes.name',read_only=True)
    # 因继承ModelSerializer所以不用写序列化器的字段，直接映射model表中的属性
    # id = serializers.IntegerField(label='ID', read_only=True)  # read_only=True只读
    # name = serializers.CharField(max_length=30, label='姓名')
    # age = serializers.IntegerField(label='年龄', required=False)  # required=False 非必填字段
    # sex = serializers.IntegerField(label='性别', required=False)
    # create_time = serializers.DateTimeField(label='创建时间')
    # update_time = serializers.DateTimeField(label='更新时间')
    # is_delete = serializers.BooleanField(label='逻辑删除')
    class Meta:
        model = Student
        # fields = '__all__'
        # fields = ['id','name','age','sex']
        exclude = ['is_delete']
        extra_kwargs = {
            'age': {'min_value': 0, 'max_value': 200}
        }

        # def validate_name(self, value):
        #     if 'mq' not in value.lower():
        #         raise serializers.ValidationError('用户名需要有mq')
        #     return value

    def validate(self, data):
        if 'mq' not in data['name']:
            raise serializers.ValidationError('用户名需要有mq')
        elif data['age'] < 18:
            raise serializers.ValidationError('年龄需要大于18')
        return data

class StudentSerializerSimple(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['name','age','sex']

class ClassSerializer(serializers.ModelSerializer):
    student_set = StudentSerializerSimple(many=True,read_only=True)
    class Meta:
        model = Classes
        # fields = '__all__'
        exclude = ['is_delete']



# class MessageSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = message
#         fields = '__all__'



